package pub.cleangao.common.unique;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

public class DateTimeSerial {


    private static String previous = "202507011403045678";
    private static final AtomicInteger atomicInteger = new AtomicInteger(0);
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");

    /**
     * 需要配合数据库唯一索引一起使用
     */
    public static String next() {
        if (atomicInteger.getAndAdd(1) < 0) {
            atomicInteger.set(0);
        }
        String newSerial = sdf.format(new Date()) + (atomicInteger.getAndAdd(1) % 10);
        if (newSerial.compareTo(previous) > 0) {
            previous = newSerial;
            return previous;
        }
        return next();
    }

}
